package com.warmlight.voicepacket.ui.user;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetBehavior;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.warmlight.voicepacket.R;
import com.warmlight.voicepacket.adapter.MyCoverDetailNetAdpter;
import com.warmlight.voicepacket.base.BaseActivity;
import com.warmlight.voicepacket.data.PlaydeatalData;
import com.warmlight.voicepacket.data.RecommendFeed;
import com.warmlight.voicepacket.data.UserCoverDetailData;
import com.warmlight.voicepacket.data.eventbus.AudioCompleted;
import com.warmlight.voicepacket.data.eventbus.NotifyMyPlaylist;
import com.warmlight.voicepacket.data.eventbus.NotifyPlayDetal;
import com.warmlight.voicepacket.data.eventbus.PlayerServiceData;
import com.warmlight.voicepacket.fragment.CopyShareFragment;
import com.warmlight.voicepacket.http.Callback;
import com.warmlight.voicepacket.http.HttpClient;
import com.warmlight.voicepacket.http.HttpConfig;
import com.warmlight.voicepacket.http.HttpUtils;
import com.warmlight.voicepacket.http.ResponseData;
import com.warmlight.voicepacket.ui.Add2NetListActivity;
import com.warmlight.voicepacket.utils.ClickLog;
import com.warmlight.voicepacket.utils.GlideCornerTransform;
import com.warmlight.voicepacket.utils.JSONUtils;
import com.warmlight.voicepacket.utils.SPUtils;
import com.warmlight.voicepacket.utils.ShareCollectCallBackUtils;
import com.warmlight.voicepacket.widget.dslv.DragSortListView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import okhttp3.Call;

/**
 * 登录后我的播单的详情页面
 */
public class MyCoverDetailOnNetActivity extends BaseActivity implements View.OnClickListener {

    private DragSortListView footerListView;
    private View vHead;
    private LinearLayout ll_header;
    private MyCoverDetailNetAdpter adapter=null;
    private LinearLayout ll_play_all, ll_share ,ll_back;
    private TextView tv_desc,tv_header_title,tv_header_titlename;
    private ImageView iv_playimg;
//    private  boolean ISBODAN=true;//播单页面
//    private  PlaydeatalData.DataBean.ShareBean sharedata;
//    private List<PlaydeatalData.DataBean.ListBean> listBean;
    private  List<PlaydeatalData.DataBean.ListBean> datas=new ArrayList<>();
//    public static final int UPDATE = 0x1;
//    private int page=1;
    private ImageView iv_cover_mine;
    private boolean isManager;
    private TextView tv_cancel;
    private TextView tv_select_all;
    private ImageView iv_back;
    private LinearLayout ll_manager;
    private RelativeLayout rl_cover_add;
    private RelativeLayout rl_cover_delete;
    private String coverId;
    private boolean isDrop = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_cover_detail_on_net);
        initView();
        initListener();
        Bundle bundle = getIntent().getExtras();
        if (bundle != null){
            coverId = bundle.getString("cover_id");
        }
        initData();
        EventBus.getDefault().register(this);
    }

    @Subscribe (threadMode = ThreadMode.MAIN)//(sticky = true)
    public void onEvent(AudioCompleted data){

        if(datas!=null&&adapter!=null){
            for (int j = 0;j<datas.size();j++){
                datas.get(j).setCheak(false);
                datas.get(j).setPause(false);
            }
            adapter.notifyDataSetChanged();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void XXX(NotifyPlayDetal messageEvent) {
        if (messageEvent.getMessage()=="share"){
            messageEvent.getListBean();
            try {

                new CopyShareFragment().show(getSupportFragmentManager(), "Dialog");
            }catch (Exception e){
                //解决 IllegalStateException: Can not perform this action after onSaveInstanceState
                e.printStackTrace();
            }
        }else if (messageEvent.getMessage()=="remove"){//这里需要加入删除数据库的操作
            PlaydeatalData.DataBean.ListBean listBean = messageEvent.getListBean();
//            for (int i=0;i<datas.size();i++){
//
//                if (datas.get(i).getId().equals(messageEvent.getListBean().getId())){
////                    Toast.makeText(getThis(),datas.get(i).getId(),Toast.LENGTH_SHORT).show();
//                    datas.remove(i);
//                    adapter.notifyDataSetChanged();//TODO
////                    DBHelper.getInstance(getThis()).delAudios();
////                    adapter.setList(listBean);
////                    Toast.makeText(getThis(),"删除成功",Toast.LENGTH_SHORT).show();
////                    delAudio(mPlaylistData.getId()+"",messageEvent.getListBean().getId());
////                    delAudioIds.add(messageEvent.getListBean().getId());
//                    Toast.makeText(getThis(),"删除成功",Toast.LENGTH_SHORT).show();
//                    break;
//                }
//            }
            ArrayList<PlaydeatalData.DataBean.ListBean> a = new ArrayList<>();
            a.add(listBean);
            deleteAudio(a);

        }else if (messageEvent.getMessage()=="public"){
            PlaydeatalData.DataBean.ListBean listBean = messageEvent.getListBean();
            setPublicOrPrivate(listBean);
        }else {//
            RecommendFeed.DataBean.ListBean bean= new RecommendFeed.DataBean.ListBean();
            for (int i = 0; i < datas.size(); i++) {
                if (messageEvent.getListBean().getId().equals(datas.get(i).getId())){
                    PlaydeatalData.DataBean.ListBean mbean =datas.get(i);

                    bean.setDuration(mbean.getDuration());
                    bean.setCategory_id(mbean.getCover_id());
                    bean.setId(mbean.getId());
                    bean.setCollect(mbean.getCollect());
                    bean.setShare(mbean.getShare());
                    bean.setStar(mbean.getStar());
                    bean.setTitle(mbean.getTitle());
                    bean.setUrl(mbean.getUrl());
                    bean.setCover_pic(mbean.getPic());
                    bean.setType(mbean.getType());
                    bean.setCover_name(mbean.getCover_name());

                    Intent addIntent = new Intent(getThis(), Add2NetListActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("audio_id",bean);
                    addIntent.putExtras(bundle);
                    getThis().startActivity(addIntent);
                }
            }

        }
    }

    private void setPublicOrPrivate(final PlaydeatalData.DataBean.ListBean listBean){
        String is_open = listBean.getIs_open();
        String url = HttpConfig.AUDIO_SET_OPEN;
        final TreeMap<String,String> treeMap = new TreeMap<>();
        treeMap.put("member_audio_id",listBean.getId());
        if (TextUtils.equals("1",is_open)){
            treeMap.put("is_open","-1");
        }else{
            treeMap.put("is_open","1");
        }
        HttpClient.getInstance().postRxAndroidAES(url,treeMap)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseData>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseData responseData) {
                        if (HttpUtils.isCodeSuccess(responseData.getCode())){
//                            listBean.setIs_open(treeMap.get("is_open"));
                            adapter.setPublic(listBean.getId(),treeMap.get("is_open"));
                            if (TextUtils.equals("-1",treeMap.get("is_open"))){
                                showToast("已设置为私密");
                            }else {
                                showToast("已设置为公开");
                            }
                        }else{
                            showToast(responseData.getMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void deleteAudio(final ArrayList<PlaydeatalData.DataBean.ListBean> listBean) {
        String json = getJson(listBean);
        String user_del_audio = HttpConfig.USER_DEL_AUDIO;
        TreeMap<String,String> treeMap = new TreeMap<>();
        treeMap.put("auth_key", SPUtils.getLoginAuthKey());
        treeMap.put("type","2");
        treeMap.put("id_list",json);
        treeMap.put("member_cover_id",coverId);
        HttpClient.getInstance().postRxAndroidAES(user_del_audio,treeMap)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseData>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseData responseData) {
                        if (TextUtils.equals("200",responseData.getCode())){
                            EventBus.getDefault().post(new NotifyMyPlaylist("net"));
                            ArrayList<String> a = new ArrayList<>();
                            for (int i= 0;i<listBean.size();i++){
                                a.add(listBean.get(i).getId());
                            }
                            deleteAudioRefresh(a);
                            showToast("移除成功");
                            ShareCollectCallBackUtils.collectCallBack(a,"-1",coverId);
                        }else{
                            showToast(responseData.getMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        showToast("删除失败，请稍后再试");
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void deleteAudioRefresh(ArrayList<String> listBean) {


        adapter.deleteList(listBean);


    }

    //音频ID list [{"id":"id", "type":"type"}]
    private String getJson(ArrayList<PlaydeatalData.DataBean.ListBean> listBean){

        JSONArray jsonArray = new JSONArray();
        for (int i =0;i<listBean.size();i++){
            PlaydeatalData.DataBean.ListBean bean = listBean.get(i);
            String id = bean.getId();
            String type = bean.getType();
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("id",id);
                jsonObject.put("type",type);
                jsonArray.put(jsonObject);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        return jsonArray.toString();
    }

    @SuppressLint("CheckResult")
    private void initData() {
        String url = HttpConfig.USER_COVER_DETAIL;
        TreeMap<String,String> treeMap = new TreeMap<>();
        treeMap.put("member_cover_id",coverId);
        treeMap.put("page","-1");
        treeMap.put("pagesize","-1");
        treeMap.put("auth_key", SPUtils.getLoginAuthKey());
        HttpClient.getInstance().postRxAndroidAES(url,treeMap)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<ResponseData>() {
                    @Override
                    public void accept(ResponseData responseData) throws Exception {
                        String code = responseData.getCode();
                        if (TextUtils.equals("200",code)){
                            String data = responseData.getData();
                            UserCoverDetailData userCoverDetailData = new Gson().fromJson(data, UserCoverDetailData.class);
                            setData(userCoverDetailData);
                        }else{
                            showToast(responseData.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {

                    }
                });
    }

    private void setData(UserCoverDetailData userCoverDetailData){
        UserCoverDetailData.InfoBean info = userCoverDetailData.getInfo();
        List<UserCoverDetailData.ListBean> list = userCoverDetailData.getList();
        if ("我的最爱".equals(info.getName())){
            iv_cover_mine.setVisibility(View.VISIBLE);
        }else{
            iv_cover_mine.setVisibility(View.GONE);
        }
        tv_header_title.setText(info.getName());

        datas= changeData(list,info);
        if(adapter==null){
            adapter = new MyCoverDetailNetAdpter(getThis(),datas, getSupportFragmentManager(),true);
            footerListView.setAdapter(adapter);
        }

//        if (datas.size()>0){
//            if (TextUtils.isEmpty(datas.get(0).getPic())){
//                Glide.with(this).load(R.drawable.icon_iv_fail).transform(new GlideCornerTransform(this, 8)).dontAnimate().into(iv_playimg);
//            }else {
        RequestOptions options = new RequestOptions();
        options.transform(new GlideCornerTransform(this,8)).dontAnimate();
                Glide.with(this).load(info.getAvator()).apply(options).into(iv_playimg);
//            }
//        }else {
//            Glide.with(this).load(R.drawable.icon_iv_fail).transform(new GlideCornerTransform(this,8)).dontAnimate().into(iv_playimg);
//        }
        initDataMine(info);
    }

    private void initDataMine(UserCoverDetailData.InfoBean info){
        tv_desc.setText("(共"+info.getAudio_num()+"首)");
    }

    private List<PlaydeatalData.DataBean.ListBean> changeData(List<UserCoverDetailData.ListBean> localData, UserCoverDetailData.InfoBean info){
        List<PlaydeatalData.DataBean.ListBean> listBeans=new ArrayList<>();
        for (int i=0; i<localData.size();i++){
            PlaydeatalData.DataBean.ListBean bean=new PlaydeatalData.DataBean.ListBean();
            bean.setId(localData.get(i).getId());
            bean.setCover_id(localData.get(i).getCover_id());
//            listBeans.get(i).set(localData.get(i).getAudio_ps();
            bean.setTitle(localData.get(i).getTitle());
            bean.setUrl(localData.get(i).getUrl());
            bean.setPic(info.getAvator());
            bean.setCover_name(localData.get(i).getCover_name());
            bean.setType(localData.get(i).getType());
            bean.setStatus(localData.get(i).getStatus());
            bean.setIs_open(localData.get(i).getIs_open());
            listBeans.add(bean);
        }
        return  listBeans;
    }

    private void initListener() {
        footerListView.setDropListener(new DragSortListView.DropListener() {
            @Override
            public void drop(int from, int to) {
                if (from != to) {
//                    DragSortListView list = getListView();
                    PlaydeatalData.DataBean.ListBean item = (PlaydeatalData.DataBean.ListBean) adapter.getItem(from);
                    adapter.remove(from);
                    adapter.insert(item, to);
                    isDrop = true;
//                    list.moveCheckState(from, to);
//                    Log.d("DSLV", "Selected item is " + list.getCheckedItemPosition());
                }
            }
        });
        footerListView.setDragListener(new DragSortListView.DragListener() {
            @Override
            public void drag(int from, int to) {
                if (from != to) {
//                    DragSortListView list = getListView();
//                    String item = adapter.getItem(from);
//                    adapter.remove(item);
//                    adapter.insert(item, to);
//                    list.moveCheckState(from, to);
//                    Log.d("DSLV", "Selected item is " + list.getCheckedItemPosition());
                }
            }
        });
        footerListView.setDragEnabled(false);
        rl_cover_delete.setOnClickListener(this);
        rl_cover_add.setOnClickListener(this);
    }

    private void initView() {

        footerListView = (DragSortListView) findViewById(R.id.flv_play);
        vHead = View.inflate(this, R.layout.header_playdetal_mine, null);

        ll_header = (LinearLayout) vHead.findViewById(R.id.ll_header);
//        ll_play_all = (LinearLayout) vHead.findViewById(R.id.ll_play_all);
        ll_share = (LinearLayout) vHead.findViewById(R.id.ll_share);
        ll_share.setOnClickListener(this);
        tv_desc = (TextView) vHead.findViewById(R.id.tv_desc);
        iv_playimg = (ImageView) vHead.findViewById(R.id.iv_playimg);
        iv_cover_mine = (ImageView) vHead.findViewById(R.id.iv_cover_mine);
        tv_header_title = (TextView) vHead.findViewById(R.id.tv_header_title);
        tv_header_titlename= (TextView) findViewById(R.id.tv_header_titlename);
        ll_back= (LinearLayout) findViewById(R.id.ll_back);
        ll_back.setOnClickListener(this);
        tv_select_all = (TextView) findViewById(R.id.tv_select_all);
        tv_select_all.setVisibility(View.GONE);
        tv_cancel = (TextView) findViewById(R.id.tv_cancel);
        iv_back = (ImageView) findViewById(R.id.iv_back);
        tv_select_all.setOnClickListener(this);
        ll_manager = (LinearLayout) findViewById(R.id.ll_manager);
        ll_manager.setVisibility(View.GONE);
        rl_cover_delete = (RelativeLayout) findViewById(R.id.rl_cover_delete);
        rl_cover_add = (RelativeLayout) findViewById(R.id.rl_cover_add);

//        if (ISBODAN) {
        tv_header_titlename.setText("我的播单");
//            tv_desc.setVisibility(View.GONE);
//            ll_share.setVisibility(View.GONE);
//        } else {
//            tv_header_titlename.setText("播单");
//        };

        footerListView.addHeaderView(ll_header);

        footerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (i==0||i==datas.size()+1)return;
                if (isManager){
                    selectItem(i-1);
                    return;
                }

                PlaydeatalData.DataBean.ListBean listBean = datas.get(i - 1);

                if (TextUtils.equals("-1",listBean.getStatus())){
                    showToast("该条音频审核未通过，暂不能播放");
                    return;
                }

                if (datas.get(i-1).isCheak()){
                    datas.get(i-1).setCheak(false);
                    datas.get(i-1).setPause(true);
                }else{
                    if (!datas.get(i-1).isPause()){
                        ClickLog.clickLog(ClickLog.myclot_feed_play,datas.get(i-1).getCover_id(),
                                datas.get(i-1).getId());
                    }

                    for (int j = 0;j<datas.size();j++){
                        datas.get(j).setCheak(false);
                        datas.get(j).setPause(false);
                    }
                    datas.get(i-1).setCheak(true);
                }

                adapter.notifyDataSetChanged();

                EventBus.getDefault().post(new PlayerServiceData(PlayerServiceData.PLAY,datas.get(i-1).getUrl()));
                //FIXME 我先埋上，重复统计待修复
//                if(ISBODAN){
//                    //本地播单feed播放单击
//                    MobclickAgent.onEvent(getThis().getApplicationContext(), MobClickHelper.MYCLOT_FEED_PLAY,datas.get(i-1).getTitle());
//                    HashMap<String,Object> temp = new HashMap<>();
//                    temp.put("本地播单feed播放单击",datas.get(i-1).getTitle().toString());
//                    ZhugeSDK.getInstance().track(getThis().getApplicationContext(),MobClickHelper.MYCLOT_FEED_PLAY,temp);
//
//                }else{
//                    //网络播单
//                    MobclickAgent.onEvent(getThis().getApplicationContext(), MobClickHelper.BAG_FEED_PLAY,datas.get(i-1).getTitle());
//                    HashMap<String,Object> temp = new HashMap<>();
//                    temp.put("网络播单",datas.get(i-1).getTitle().toString());
//                    ZhugeSDK.getInstance().track(getThis().getApplicationContext(),MobClickHelper.BAG_FEED_PLAY,temp);
//
//                }
            }
        });


    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.ll_share:
                if (datas.size()==0){
                    break;
                }
                isManager = true;
                footerListView.setDragEnabled(true);
//                new CustomBottomSheetDialogFragment(sharedata).show(getSupportFragmentManager(), "Dialog");//展示分享弹窗
//                Toast.makeText(PlayDetailMineActivity.this,"管理",Toast.LENGTH_LONG).show();
                ll_share.setVisibility(View.GONE);
                iv_back.setVisibility(View.GONE);
                tv_cancel.setVisibility(View.VISIBLE);
                tv_select_all.setVisibility(View.VISIBLE);
                ll_manager.setVisibility(View.VISIBLE);
                startManager();
                break;
            case R.id.ll_back://bar 返回键
                if (isManager){
                    isManager = false;
                    footerListView.setDragEnabled(false);
                    ll_share.setVisibility(View.VISIBLE);
                    iv_back.setVisibility(View.VISIBLE);
                    tv_cancel.setVisibility(View.GONE);
                    tv_select_all.setVisibility(View.GONE);
                    ll_manager.setVisibility(View.GONE);
                    //取消
                    cancelManager();
                    tv_select_all.setText("全选");
                    //排序更新
                    if (isDrop) {
                        isDrop = false;
                        refreshSort();
                    }
                }else{
                    finish();
                }
//                if(ISBODAN){
//                    delAudio4List(mPlaylistData.getId()+"",delAudioIds);
//                }
//                finish();
                break;
            case R.id.tv_select_all:
                //全选
                if ("全选".equals(tv_select_all.getText())){
                    selectAll();
                    tv_select_all.setText("取消\n全选");
                }else{
                    cancelSelectAll();
                    tv_select_all.setText("全选");
                }
                break;
            case R.id.rl_cover_delete:
                deleteCover();
                break;
            case R.id.rl_cover_add:
                addCover();
                break;
        }
    }

    private void addCover() {
        if (adapter != null){
            ArrayList<PlaydeatalData.DataBean.ListBean> select2 = adapter.getSelect2();
            if (select2.size()> 0){
//                delAudio4List(mPlaylistData.getId()+"",select2);
                Intent addIntent = new Intent(getThis(), Add2NetListActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("net_cover",select2);
                addIntent.putExtras(bundle);
                getThis().startActivity(addIntent);
            }else{
                showToast("请选择要收藏的音频");
            }
        }
    }

    private void refreshSort(){
        if (adapter != null){
            ArrayList<String> allId = adapter.getAllId();


            String json = toJson(allId);


        String url = HttpConfig.SYNC_DATA;
        TreeMap<String,String> treeMap = new TreeMap<>();
        treeMap.put("audio_list",json);
        treeMap.put("member_cover_name",tv_header_title.getText().toString());
        treeMap.put("auth_key", SPUtils.getLoginAuthKey());
        HttpClient.post(url, treeMap, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
////                        hideProgressDialog();
////                        showToast("上传音频失败，请重试");
//                    }
//                });
            }

            @Override
            public void onResponse(Call call, String response)   {
//                String post = response.body().string();
                if (!TextUtils.isEmpty(response)){
                    ArrayList<Map<String, String>> listMapByJson = JSONUtils.getListMapByJson(response);
                    if (listMapByJson.size()>0){
                        Map<String, String> map = listMapByJson.get(0);
                        if (TextUtils.equals("200",map.get("code"))){

//                            runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
////                                    hideProgressDialog();
////                                    EventBus.getDefault().post(new NotifyMyPlaylist("net"));
////                                    showToast("上传音频成功");
//                                }
//                            });

                        }else{

                        }
                    }
                }
            }
        });
        }



//        DBFloatPlaylist data = DBFloatPlayListDaoHelp.queryBuilderById(getThis(),mPlaylistData.getId()+"");
//        if(data!=null){
//
//            StringBuffer result = new StringBuffer();
//            for(PlaydeatalData.DataBean.ListBean resultId : datas){
//                result.append(resultId.getId());
//                result.append(",");
//            }
//
//            String newAudios = "";
//            if(result!=null&&result.length()>0){
//                newAudios = result.substring(0,result.length()-1);
//            }
////            newAudios = result.toString();
//            data.setList_audio(newAudios);
//            data.setList_count(String.valueOf(datas.size()));
//
//            //FIXME 此方法会修改播单的_id
////            DBHelper.getInstance(getThis()).delPlayList(playlistID);
////            DBHelper.getInstance(getThis()).addList(data);
//            DBFloatPlayListDaoHelp.update(getThis(),data);
//
//            EventBus.getDefault().post(new NotifyMyPlaylist("notify"));
//        }
    }

    private String toJson(ArrayList<String> allId){
        JSONArray jsonArray = new JSONArray();
        if (allId.size()==0){

        }else {
            for (String s : allId) {
                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.put("id", s);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    jsonArray.put(jsonObject);



            }
        }
        return jsonArray.toString();
    }
    private ProgressDialog progressDialog;
    private void showProgressDialog(){
        if (progressDialog == null){
            progressDialog = new ProgressDialog(this,android.R.style.Theme_Material_Light_Dialog_Alert);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.setCancelable(false);
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.setMessage("加载数据中");
        }

        progressDialog.show();
    }

    private void hideProgressDialog(){
        if (progressDialog != null){
            if (progressDialog.isShowing()){
                progressDialog.dismiss();
            }
        }
    }

    private void deleteCover(){
        if (adapter != null){
            final ArrayList<PlaydeatalData.DataBean.ListBean> select2 = adapter.getSelect2();
            if (select2.size()> 0){
//                showProgressDialog();
//                Observable.create(new ObservableOnSubscribe<Object>() {
//                    @Override
//                    public void subscribe(ObservableEmitter<Object> emitter) throws Exception {
////                        delAudio4List(mPlaylistData.getId()+"",select2);
//
//                        emitter.onNext("");
//                        emitter.onComplete();
//                    }
//                }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
//                        .subscribe(new Observer<Object>() {
//                            @Override
//                            public void onSubscribe(Disposable d) {
//
//                            }
//
//                            @Override
//                            public void onNext(Object o) {
//                                hideProgressDialog();
//                                EventBus.getDefault().post(new NotifyMyPlaylist("notify"));
//                                adapter.deleteList(select2);
//                            }
//
//                            @Override
//                            public void onError(Throwable e) {
//
//                            }
//
//                            @Override
//                            public void onComplete() {
//
//                            }
//                        });

                deleteAudio(select2);

            }else{
                showToast("请选择要删除的音频");
            }
        }
    }

    private void selectItem(int position){
        if (adapter != null){
            adapter.selectItem(position);
        }
    }

    private void cancelSelectAll(){
        if (adapter != null){
            adapter.cancelSelectAll();
        }
    }

    private void cancelManager(){
        if (adapter != null){
            adapter.cancelManager();
        }

    }

    private void startManager(){
        if (adapter != null){
            adapter.startManager();
        }
    }

    private void selectAll(){
        if (adapter != null){
            adapter.selectAll();
        }
    }

    private void showBottomSheet(BottomSheetBehavior behavior) {
        if (behavior.getState() == BottomSheetBehavior.STATE_HIDDEN) {
            behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
        } else {
            behavior.setState(BottomSheetBehavior.STATE_HIDDEN);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onBackPressed() {
        if (isManager){

        }else {
            super.onBackPressed();
        }
    }




    //以下代码解决 IllegalStateException: Can not perform this action after onSaveInstanceState

    private Method noteStateNotSavedMethod;
    private Object fragmentMgr;
    private String[] activityClassName = {"Activity", "FragmentActivity"};

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        invokeFragmentManagerNoteStateNotSaved();
    }

    private void invokeFragmentManagerNoteStateNotSaved() {
        //java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
            return;
        }
        try {
            if (noteStateNotSavedMethod != null && fragmentMgr != null) {
                noteStateNotSavedMethod.invoke(fragmentMgr);
                return;
            }
            Class cls = getClass();
            do {
                cls = cls.getSuperclass();
            } while (!(activityClassName[0].equals(cls.getSimpleName())
                    || activityClassName[1].equals(cls.getSimpleName())));

            Field fragmentMgrField = prepareField(cls, "mFragments");
            if (fragmentMgrField != null) {
                fragmentMgr = fragmentMgrField.get(this);
                noteStateNotSavedMethod = getDeclaredMethod(fragmentMgr, "noteStateNotSaved");
                if (noteStateNotSavedMethod != null) {
                    noteStateNotSavedMethod.invoke(fragmentMgr);
                }
            }

        } catch (Exception ex) {
        }
    }

    private Field prepareField(Class<?> c, String fieldName) throws NoSuchFieldException {
        while (c != null) {
            try {
                Field f = c.getDeclaredField(fieldName);
                f.setAccessible(true);
                return f;
            } finally {
                c = c.getSuperclass();
            }
        }
        throw new NoSuchFieldException();
    }

    private Method getDeclaredMethod(Object object, String methodName, Class<?>... parameterTypes) {
        Method method = null;
        for (Class<?> clazz = object.getClass(); clazz != Object.class; clazz = clazz.getSuperclass()) {
            try {
                method = clazz.getDeclaredMethod(methodName, parameterTypes);
                return method;
            } catch (Exception e) {
            }
        }
        return null;
    }
}
